package com.imu.upload.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@RestController
@RequestMapping("/download")
public class DownloadController {
    @Value("${file.upload-base-path}")
    String path;
    @GetMapping
    public void download(String name , HttpServletResponse response) throws IOException {
        String pathFile =path+name;
        File file = new File(pathFile);
        byte[] bytes = new byte[1024];
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("image/jpeg");
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            int len=0;
            while ((len = fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            fileInputStream.close();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    }


